package com.work.storage.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.work.storage.entity.Storage;
import com.work.storage.repository.StorageDAO;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.spring.annotation.GlobalLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author YonJar
 * @date 2024/6/12.
 * @description
 */
@Slf4j
@Service
public class TccStorageServiceImpl implements TccStorageService{

    @Resource
    private StorageDAO storageDAO;

//    @GlobalLock
    @Transactional
    @Override
    public boolean prepare(BusinessActionContext context, String commodityCode, Integer count) {
        //校验 select for update
        QueryWrapper<Storage> wrapper = new QueryWrapper<>();
        wrapper.setEntity(new Storage().setCommodityCode(commodityCode));
        Storage storage = storageDAO.selectOne(wrapper);
//        storage.setCount(storage.getCount() - count);

        log.info("########### 打印，XID = " + context.getXid());
        log.info("################ storage prepare ################ ");
        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext context) {
        Map<String, Object> actionContext = context.getActionContext();
        String commodityCode= (String) actionContext.get("commodityCode");
        Integer count= (Integer) actionContext.get("count");

        QueryWrapper<Storage> wrapper = new QueryWrapper<>();
        wrapper.setEntity(new Storage().setCommodityCode(commodityCode));
        Storage storage = storageDAO.selectOne(wrapper);

        storage.setCount(storage.getCount() - count);
        storageDAO.updateById(storage);

        log.info("################ storage commit ################ ");
        return true;
    }

    /**
     * 回滚，把之前 减掉的金额，加回去
     * @param context
     * @return
     */
    @Transactional
    @Override
    public boolean rollback(BusinessActionContext context) {
        Map<String, Object> actionContext = context.getActionContext();
        String commodityCode= (String) actionContext.get("commodityCode");
        Integer count= (Integer) actionContext.get("count");

        QueryWrapper<Storage> wrapper = new QueryWrapper<>();
        wrapper.setEntity(new Storage().setCommodityCode(commodityCode));
        Storage storage = storageDAO.selectOne(wrapper);

        storage.setCount(storage.getCount() + count);
        storageDAO.updateById(storage);

        log.info("################ storage rollback ################ ");
        return true;
    }
}
